#include <SDL.h>
#include <SDL_ttf.h>
#include "scr_font.h"
#include "scr_game.h"

SCRFont::SCRFont(const std::string& Filename, const int& Size)
	: SCRResource()
	, m_pFont(NULL)
	, m_Color(0xFFFFFFFF)
	, m_BackgroundColor(0x0)
{
	m_pFont = TTF_OpenFont(Filename.c_str(), Size);
	if (m_pFont)
	{
		m_Filename = Filename;
		m_Size = Size;
		m_IsValid = true;
	}
}

SCRFont::~SCRFont()
{
	if (m_pFont)
	{
		TTF_CloseFont(m_pFont);
	}
}

void SCRFont::Draw(const int& X, const int& Y, const std::string& Text, 
	const SCRFontType::Enum& Type, const SCRFontAlign::Flag& Align)
{
	SDL_Color TextColor = { (m_Color & 0xFF0000) >> 16, (m_Color & 0xFF00) >> 8, m_Color & 0xFF };
	SDL_Surface* TextSurface = NULL;
	if (SCRFontType::SOLID == Type)
	{
		TextSurface = TTF_RenderText_Solid(m_pFont, Text.c_str(), TextColor);
	}
	else if (SCRFontType::SHADED == Type)
	{
		SDL_Color BackgroundColor = { (m_BackgroundColor & 0xFF0000) >> 16, 
			(m_BackgroundColor & 0xFF00) >> 8, m_BackgroundColor & 0xFF };
		TextSurface = TTF_RenderText_Shaded(m_pFont, Text.c_str(), TextColor, BackgroundColor);
	}
	else if (SCRFontType::BLENDED == Type)
	{
		TextSurface = TTF_RenderText_Blended(m_pFont, Text.c_str(), TextColor);
	}

	if (TextSurface)
	{
		int AlignX = 0;
		int AlignY = 0;

		if (Align & SCRFontAlign::CENTER_X)
		{
			AlignX = TextSurface->w >> 1; 
		}
		else if (Align & SCRFontAlign::RIGHT)
		{
			AlignX = TextSurface->w;
		}

		if (Align & SCRFontAlign::CENTER_Y)
		{
			AlignY = TextSurface->h >> 1;
		}
		else if (Align & SCRFontAlign::BOTTOM)
		{
			AlignY = TextSurface->h;
		}
		
		SDL_Rect Position = { (Sint16)X - AlignX, (Sint16)Y - AlignY, 0, 0 };
		SDL_BlitSurface(TextSurface, NULL, SCRGame::GetInstance()->GetScreen(), &Position);
		SDL_FreeSurface(TextSurface);
	}
}
